package com.erp.gather.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.erp.gather.service.AliexpressCategoryService;
import com.erp.gather.mapper.ErpCollectProductMapper;
import com.erp.gather.domain.*;
import com.erp.gather.mapper.*;
import com.ruoyi.ae.api.RemoteAeCategoryService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.gather.api.domain.Aliexpress;
import com.ruoyi.gather.api.domain.ErpCollectProduct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Service
public class AliexpressCategoryServiceImpl implements AliexpressCategoryService {
    private final ErpCollectProductCategoryMapper erpCollectProductCategoryMapper;
    private final ErpCollectProductCategoryValueJoinMapper categoryValueJoinMapper;
    private final ErpCollectProductCategoryKeyValueMapper keyValueMapper;
    private final ErpCollectProductCategoryKeyMapper keyMapper;
    private final ErpCollectProductCategoryValueMapper valueMapper;
    private final ErpCollectProductMapper erpCollectProductMapper;

    @Resource
    RemoteAeCategoryService remoteAeCategoryService;


    @Override
    public void saveAliexpressCategory() {
        List<ErpCollectProductCategoryValueJoin> list = new ArrayList<ErpCollectProductCategoryValueJoin>();

        List<Long> ids = erpCollectProductCategoryMapper
                .selectList(Wrappers.lambdaQuery(new ErpCollectProductCategory())
                        .eq(ErpCollectProductCategory::getIsleaf, true).orderByDesc(ErpCollectProductCategory::getId))
                .stream().map(ErpCollectProductCategory::getId).collect(Collectors.toList());
        for (Long id : ids) {
            //TODO 待改造为内部类调用 待测试
//            String res = HttpUtil.get(aeConfig.getEndpoint() + "/aliexpress/category/getById?categoryId=" + id);
            R<String> resObj = remoteAeCategoryService.getByCategoryId(id.toString());
            if (resObj.getCode() != 200) {
                log.error("调用接口异常");
                return;
            }
            String res = resObj.getData();
            Aliexpress.AliexpressCategoryResponse aliexpressCategoryResponse = JSONObject.parseObject(res,
                    Aliexpress.AliexpressCategoryResponse.class);
            List<Aliexpress.AttributeDto> attributeDtoList = aliexpressCategoryResponse
                    .getAliexpressCategoryRedefiningGetchildattributesresultbypostcateidandpathResponse().getResult()
                    .getAttributes().getAeopAttributeDto();

            for (Aliexpress.AttributeDto attributeDto : attributeDtoList) {

                Long nameId = attributeDto.getId();
                if (nameId.equals(2l)) {
                    continue;
                }
                List<Aliexpress.AttrValueDto> attrValueDtoList = attributeDto.getValues().getAeopAttrValueDto();
                if (attrValueDtoList != null) {
                    for (Aliexpress.AttrValueDto attrValueDto : attrValueDtoList) {
                        Long valueId = attrValueDto.getId();
                        ErpCollectProductCategoryValueJoin join = new ErpCollectProductCategoryValueJoin();
                        join.setCategoryId(id);
                        join.setParentId(nameId);
                        join.setValueId(valueId + "");
                        list.add(join);
                        if (list.size() % 500 == 0) {
                            categoryValueJoinMapper.insertBatch(list);
                            list.clear();
                        }
                    }
                }
            }
        }
        categoryValueJoinMapper.insertBatch(list);
    }

    @Override
    public List<Aliexpress.CategoryInfoVo> getCategoryInfoById(Long id, Boolean isSku) {

        List<Aliexpress.CategoryInfoVo> list1 = new ArrayList<>();

        List<ErpCollectProductCategoryKeyValue> keyValueList = null;
        // 判断数据库是否有
        LambdaQueryWrapper<ErpCollectProductCategoryKeyValue> lqw = new LambdaQueryWrapper<ErpCollectProductCategoryKeyValue>();
        lqw.eq(ErpCollectProductCategoryKeyValue::getCategoryId, id);
        lqw.groupBy(ErpCollectProductCategoryKeyValue::getCategoryId);
        lqw.groupBy(ErpCollectProductCategoryKeyValue::getKeyId);
        if (isSku)
            lqw.eq(ErpCollectProductCategoryKeyValue::getSku, "1");
        // 判断类目的时间
        ErpCollectProductCategory category = erpCollectProductCategoryMapper.selectById(id);
        DateTime time = new DateTime(category.getUpdateTime());

        DateTime plusDays = time.offsetNew(DateField.HOUR, 24);
//		if (plusDays.isBeforeNow()) { // 是否大于一星期，大于重新获取 TODO 类目更新待定
//			saveCategoryInfo(id);
//			keyValueList = keyValueMapper.selectList(lqw);
//			erpCollectProductCategoryMapper.updateById(category);
//		} else {
//			keyValueList = keyValueMapper.selectList(lqw);
//			if (keyValueList == null || keyValueList.size() == 0) {
//				saveCategoryInfo(id);
//				keyValueList = keyValueMapper.selectList(lqw);
//			}
//		}
        // TODO 类目更新待定
        keyValueList = keyValueMapper.selectList(lqw);
        if (keyValueList == null || keyValueList.size() == 0) {
            saveCategoryInfo(id);
            keyValueList = keyValueMapper.selectList(lqw);
        }

        for (ErpCollectProductCategoryKeyValue keyValue : keyValueList) {
            Long nameId = keyValue.getKeyId();

            String sku = keyValue.getSku();
            String required = keyValue.getRequired();
            if (!isSku) {
                if (sku.equals("1") && required.equals("0"))
                    continue;
            } else {
                if (sku.equals("0"))
                    continue;
            }

            Aliexpress.CategoryInfoVo vo = new Aliexpress.CategoryInfoVo();

            // 获取key的信息
            ErpCollectProductCategoryKey key = keyMapper.selectById(nameId);
            vo.setZhName(key.getZhName());
            vo.setAttr_name(key.getEnName());
            vo.setAttr_name_id(nameId);
            vo.setAttributeShowTypeValue(keyValue.getAttributeShowTypeValue());
            vo.setRequired(keyValue.getRequired());
            vo.setSku(sku);
            vo.setSpec(keyValue.getSpec());

            List<Aliexpress.ValueVo> values = new ArrayList<>();
            // 获取value的集合
            ErpCollectProductCategoryValueJoin valueJoin = categoryValueJoinMapper
                    .selectOne(new LambdaQueryWrapper<ErpCollectProductCategoryValueJoin>()
                            .eq(ErpCollectProductCategoryValueJoin::getCategoryId, id)
                            .eq(ErpCollectProductCategoryValueJoin::getParentId, nameId).last("limit 1"));
            if (valueJoin != null) {
                List<ErpCollectProductCategoryValue> valueList = valueMapper
                        .selectBatchIds(Arrays.asList(valueJoin.getValueId().split(",")));
                for (ErpCollectProductCategoryValue value : valueList) {
                    Aliexpress.ValueVo valueVo = new Aliexpress.ValueVo();

                    String enValueName = value.getEnName();
                    String zhValueName = value.getZhName();

                    valueVo.setAttr_value_id(value.getId());
                    valueVo.setZhName(zhValueName);
                    valueVo.setAttr_value(enValueName);
                    values.add(valueVo);
                }
            }
            vo.setValues(values);
            list1.add(vo);
        }

        return list1;
    }

    @Override
    public List<Aliexpress.ValueVo> getBrandById(Long categoryId, Long storeId) {
        List<Aliexpress.ValueVo> values = new ArrayList<>();
        //TODO 待改造为内部类调用 已测试完成
//        String res = HttpUtil.get(aeConfig.getEndpoint() + "/aliexpress/category/getBrandById?categoryId=" + categoryId
//                + "&storeId=" + storeId);
        R<Object> brandResult = remoteAeCategoryService.getBrandByIdInnerAuth(categoryId, storeId);
        if (R.FAIL == brandResult.getCode()) {
            throw new ServiceException(brandResult.getMsg());
        }

        String res = (String) brandResult.getData();
        Aliexpress.AliexpressCategoryResponse aliexpressCategoryResponse = JSONObject.parseObject(res,
                Aliexpress.AliexpressCategoryResponse.class);
        Aliexpress.Result response = aliexpressCategoryResponse
                .getAliexpressCategoryRedefiningGetchildattributesresultbypostcateidandpathResponse();
        if (response == null)
            return values;
        System.out.println(JSONObject.toJSONString(response));
        List<Aliexpress.AttributeDto> attributeDtoList = response.getResult().getAttributes().getAeopAttributeDto();

        if (ObjectUtils.isNull(attributeDtoList)) {
            return values;
        }

        for (Aliexpress.AttributeDto attributeDto : attributeDtoList) {

            Long nameId = attributeDto.getId();
            if (nameId.equals(2l)) {

                List<Aliexpress.AttrValueDto> attrValueDtoList = attributeDto.getValues().getAeopAttrValueDto();
                if (attrValueDtoList != null) {
                    for (Aliexpress.AttrValueDto attrValueDto : attrValueDtoList) {
                        Aliexpress.ValueVo valueVo = new Aliexpress.ValueVo();

                        Map valueNames = JSONObject.parseObject(attrValueDto.getNames(), Map.class);
                        String enValueName = (String) valueNames.get("en");
                        String zhValueName = (String) valueNames.get("zh");

                        valueVo.setAttr_value_id(attrValueDto.getId());
                        valueVo.setZhName(zhValueName);
                        valueVo.setAttr_value(enValueName);
                        values.add(valueVo);
                    }
                }
            }
        }
        return values;
    }

    public void saveCategoryInfo(Long id) {
        //TODO 待改造为内部类调用 已测试完成
        String res = null;
        R<String> resObj = remoteAeCategoryService.getByCategoryId(id.toString());
        if (resObj.getCode() != 200) {
            log.error("调用接口异常");
            return;
        }
        res = (String) resObj.getData();
        System.out.println(res);
//        String res = HttpUtil.get(aeConfig.getEndpoint() + "/aliexpress/category/getById?categoryId=" + id);
        Aliexpress.AliexpressCategoryResponse aliexpressCategoryResponse = JSONObject.parseObject(res,
                Aliexpress.AliexpressCategoryResponse.class);

//            List<Aliexpress.AttributeDto> attributeDtoList = aliexpressCategoryResponse
//                    .getAliexpressCategoryRedefiningGetchildattributesresultbypostcateidandpathResponse().getResult()
//                    .getAttributes().getAeopAttributeDto();
        Aliexpress.AliexpressCategoryResult result = aliexpressCategoryResponse
                .getAliexpressCategoryRedefiningGetchildattributesresultbypostcateidandpathResponse().getResult();
        Aliexpress.Attributes attributes = result.getAttributes();
        if (Objects.isNull(attributes)){
            return;
        }
        List<Aliexpress.AttributeDto> attributeDtoList = attributes.getAeopAttributeDto();
                // 删除
        keyValueMapper.delete(new LambdaQueryWrapper<ErpCollectProductCategoryKeyValue>()
                .eq(ErpCollectProductCategoryKeyValue::getCategoryId, id));
        categoryValueJoinMapper.delete(new LambdaQueryWrapper<ErpCollectProductCategoryValueJoin>()
                .eq(ErpCollectProductCategoryValueJoin::getCategoryId, id));

        for (Aliexpress.AttributeDto attributeDto : attributeDtoList) {

            Long nameId = attributeDto.getId();
            if (nameId.equals(2l)) {
                continue;
            }
            Map namesMap = JSONObject.parseObject(attributeDto.getNames(), Map.class);
            if (namesMap.size() == 0)
                continue;
            String enName = (String) namesMap.get("en");
            String zhName = (String) namesMap.get("zh");

            // 保存到数据库
            ErpCollectProductCategoryKey key = new ErpCollectProductCategoryKey();
            key.setId(nameId);
            key.setZhName(zhName);
            key.setEnName(enName);
            keyMapper.insertOrUpdate(key);

            ErpCollectProductCategoryKeyValue keyValue = new ErpCollectProductCategoryKeyValue();
            keyValue.setCategoryId(id);
            keyValue.setKeyId(nameId);
            keyValue.setCustomizedName(attributeDto.getCustomizedName() ? "1" : "0");
            keyValue.setVisible(attributeDto.getVisible() ? "1" : "0");
            keyValue.setCustomizedPic(attributeDto.getCustomizedPic() ? "1" : "0");
            keyValue.setKeyAttribute(attributeDto.getKeyAttribute() ? "1" : "0");
            keyValue.setInputType(attributeDto.getInputType());
            keyValue.setAttributeShowTypeValue(attributeDto.getAttributeShowTypeValue());
            keyValue.setRequired(attributeDto.getRequired() ? "1" : "0");
            keyValue.setSpec(attributeDto.getSpec());
            keyValue.setFeatures(attributeDto.getFeatures());
            keyValue.setSupportEnumInput(attributeDto.getSupportEnumInput() ? "1" : "0");
            keyValue.setSku(attributeDto.getSku() ? "1" : "0");

            keyValueMapper.insert(keyValue);

            List<Aliexpress.AttrValueDto> attrValueDtoList = attributeDto.getValues().getAeopAttrValueDto();
            if (attrValueDtoList != null) {
                String valueIds = "";
                for (Aliexpress.AttrValueDto attrValueDto : attrValueDtoList) {

                    Map valueNames = JSONObject.parseObject(attrValueDto.getNames(), Map.class);
                    String enValueName = (String) valueNames.get("en");
                    String zhValueName = (String) valueNames.get("zh");

                    ErpCollectProductCategoryValue value = new ErpCollectProductCategoryValue();
                    value.setId(attrValueDto.getId());
                    value.setParentId(nameId);
                    value.setZhName(zhValueName);
                    value.setEnName(enValueName);

                    valueMapper.insertOrUpdate(value);

                    valueIds += attrValueDto.getId() + ",";
                }

                ErpCollectProductCategoryValueJoin categoryValueJoin = new ErpCollectProductCategoryValueJoin();
                categoryValueJoin.setCategoryId(id);
                categoryValueJoin.setParentId(nameId);
                categoryValueJoin.setValueId(valueIds);
                categoryValueJoinMapper.insert(categoryValueJoin);
            }
        }
    }

    @Override
    public void updateProductAttributesById(Long id) {
        ErpCollectProduct erpCollectProduct = erpCollectProductMapper.selectById(id);
        Long categoryId = erpCollectProduct.getCategoryId();
        // List<Aliexpress.CategoryInfoVo> infoVoList =
        // getCategoryInfoById(erpCollectProduct.getCategoryId(), null, null);
        JSONArray list = JSONObject.parseArray(erpCollectProduct.getCustomAttributes());
        List<ErpCollectProductCategoryKeyValue> keyValueList = keyValueMapper
                .selectList(Wrappers.lambdaQuery(new ErpCollectProductCategoryKeyValue())
                        // .eq(ErpCollectProductCategoryKeyValue::getCategoryId, categoryId)
                );
        List<JSONObject> jsonObjectList = list.stream().map(item -> {
            System.out.println(item);
            JSONObject jsonObject = (JSONObject) item;
            String attrName = jsonObject.getString("attr_name");
            List<ErpCollectProductCategoryKey> keyList = keyMapper
                    .selectList(Wrappers.lambdaQuery(new ErpCollectProductCategoryKey())
                            .in(ErpCollectProductCategoryKey::getId, keyValueList.stream()
                                    .map(ErpCollectProductCategoryKeyValue::getKeyId).collect(Collectors.toList())));
            for (int i = 0; i < keyList.size(); i++) {
                if (Objects.equals(attrName, keyList.get(i).getEnName())) {
                    jsonObject.put("attr_name_id", keyList.get(i).getId());
                    break;
                } else {
                    jsonObject.put("attr_name_id", "-1");
                }
            }

            String attrValue = jsonObject.getString("attr_value");
            List<ErpCollectProductCategoryValue> valueList = valueMapper
                    .selectList(Wrappers.lambdaQuery(new ErpCollectProductCategoryValue())
                            // .in(ErpCollectProductCategoryValue::getParentId,
                            // keyList.stream().map(ErpCollectProductCategoryKey::getId).collect(Collectors.toList()))
                            .eq(ErpCollectProductCategoryValue::getParentId,
                                    Long.valueOf(jsonObject.getString("attr_name_id")))
                            .eq(ErpCollectProductCategoryValue::getEnName,
                                    attrValue.contains(",") ? attrValue.split(",")[0] : attrValue));
            if (valueList.size() == 0) {
                jsonObject.put("attr_value_id", "-1");
            } else {
                jsonObject.put("attr_value_id", valueList.get(0).getId());
            }
            System.out.println(jsonObject);
            return jsonObject;
        }).collect(Collectors.toList());
        // list.forEach();
        erpCollectProduct.setCustomAttributes(JSONObject.toJSONString(jsonObjectList));
        int b = erpCollectProductMapper.updateById(erpCollectProduct);
        System.out.println(b);
    }

    @Override
    public Map<Integer, List<Integer>> getSkuPropertyById(Long id) {

        List<Aliexpress.CategoryInfoVo> list = getCategoryInfoById(id, true);
        list = list.stream().filter(vo -> {
            String sku = vo.getSku();
            if (vo.getAttr_name_id().equals(14l))
                vo.setSpec(0l);
            return sku.equals("1") && !vo.getAttr_name_id().equals(200007763l);
        }).sorted(Comparator.comparing(Aliexpress.CategoryInfoVo::getSpec)).collect(Collectors.toList());

        Map<Integer, List<Integer>> resMap = new LinkedHashMap<Integer, List<Integer>>();
        for (Aliexpress.CategoryInfoVo vo : list) {

            List<Integer> values = new ArrayList<>();
            List<Aliexpress.ValueVo> valueList = vo.getValues();
            if (valueList != null) {
                for (Aliexpress.ValueVo value : valueList) {

                    values.add(value.getAttr_value_id().intValue());
                }
            }
            resMap.put(vo.getAttr_name_id().intValue(), values);
        }

        return resMap;
    }


}
